package cn.ibizlab.core.authentication.domain;

import cn.ibizlab.util.annotation.Audit;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.sql.Timestamp;
import java.time.Duration;
import java.util.Date;

@Audit
@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class AuthUserLogin implements Serializable {
    /**
     * 登录名
     */
    public String loginName;
    /**
     * 登录时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8")
    @JSONField(name = "login_time", format = "yyyy-MM-dd HH:mm:ss")
    public Timestamp loginTime;
    /**
     * 登录失败次数
     */
    public int failCount = 0;
    /**
     * 登陆ip地址
     */
    public String ipAddress;

    public long getWaitForUnlock(int maxFailCount, long timeToLive) {
        long wait = 0;
        if (failCount>=maxFailCount && loginTime != null) {
            Duration elapsed = Duration.between(loginTime.toInstant(), new Timestamp(System.currentTimeMillis()).toInstant());
            long elapsedSeconds = elapsed.getSeconds();

            // 如果已经超过基础冷却时间，则不需要再等待
            if (elapsedSeconds >= timeToLive) {
                return wait;
            }

            // 计算剩余冷却时间（秒）
            wait = timeToLive - elapsedSeconds;

            // 将剩余冷却时间转换为分钟并向上取整
            return (long) Math.ceil(wait / 60.0);
        }
        return wait;
    }
}
